<template>
  <div class="main-content">
    <div v-if="!selectedIndex" class="welcome-section">
      <div class="welcome-content">
        <div class="welcome-icon">🔍</div>
        <h2>欢迎使用 Elasticsearch SQL Client</h2>
        <p>请在左侧选择一个索引开始查询数据</p>
      </div>
    </div>
    
    <div v-else class="index-content">
      <!-- 将查询部分移到顶部 -->
      <div class="query-section">
        <div class="query-tabs">
          <button 
            @click="activeTab = 'sql'" 
            class="tab-btn" 
            :class="{ active: activeTab === 'sql' }"
          >
            SQL执行
          </button>
          <button 
            @click="activeTab = 'dsl'" 
            class="tab-btn" 
            :class="{ active: activeTab === 'dsl' }"
          >
            DSL执行
          </button>
        </div>
        
        <div class="query-content">
          <div v-if="activeTab === 'sql'" class="sql-query">
            <div class="query-hint">
              <p><strong> 提示:</strong> 如果索引名称包含特殊字符(如连字符-)，请使用方括号括起来，例如: <code>SELECT * FROM [my-index] WHERE field = 'value'</code></p>
            </div>
            <textarea 
              v-model="sqlQuery" 
              placeholder="请输入SQL查询语句，例如: SELECT * FROM [my-index] WHERE title = 'Rocky Mountain'"
              class="query-textarea"
              :disabled="executingSql"
            ></textarea>
            <div class="query-actions">
              <button 
                @click="executeSql" 
                :disabled="!isConnected || !sqlQuery.trim() || executingSql" 
                class="execute-btn"
              >
                <span v-if="executingSql">执行中...</span>
                <span v-else>▶️ 执行SQL</span>
              </button>
              <button @click="clearSql" class="clear-btn">
                🗑️ 清空
              </button>
            </div>
          </div>
          
          <div v-else class="dsl-query">
            <div class="query-hint">
              <p><strong> 提示:</strong> 支持查询/删除等DSL，注意操作风险</p>
            </div>
            <textarea 
              v-model="dslQuery" 
              placeholder="请输入DSL查询语句，例如: {&#10;  &quot;query&quot;: {&#10;    &quot;match_all&quot;: {}&#10;  }&#10;}"
              class="query-textarea"
              :disabled="executingDsl"
            ></textarea>
            <div class="query-actions">
              <button 
                @click="executeDsl" 
                :disabled="!isConnected || !dslQuery.trim() || executingDsl" 
                class="execute-btn"
              >
                <span v-if="executingDsl">执行中...</span>
                <span v-else>▶️ 执行DSL</span>
              </button>
              <button @click="clearDsl" class="clear-btn">
                🗑️ 清空
              </button>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 数据展示部分 -->
      <div class="data-section">
        <div class="index-header">
          <div class="index-title">索引：{{ selectedIndex }}</div>
          <!-- 分页控件移到数据展示部分的顶部 -->
          <div class="pagination">
            <button 
              @click="prevPage" 
              :disabled="currentPage <= 1" 
              class="pagination-btn"
            >
              上一页
            </button>
            <span class="page-info">第 {{ currentPage }} 页 / 共 {{ totalPages }} 页</span>
            <button 
              @click="nextPage" 
              :disabled="currentPage >= totalPages" 
              class="pagination-btn"
            >
              下一页
            </button>
          </div>
        </div>
        
        <div v-if="loadingData" class="loading">
          <div class="spinner"></div>
          <span>加载中...</span>
        </div>
        
        <div v-else-if="indexData.hits && indexData.hits.length > 0" class="data-table-container">
          <table class="data-table">
            <thead>
              <tr>
                <th>ID</th>
                <th>Score</th>
                <th>数据</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="hit in indexData.hits" :key="hit.id">
                <td class="text-mono">{{ hit.id }}</td>
                <td>{{ hit.score }}</td>
                <td class="source-data">
                  <div class="json-content">
                    <pre class="json-pre" v-html="formatJson(hit.source)"></pre>
                    <button @click="copyJson(hit.source)" class="copy-btn" title="复制JSON">📋</button>
                  </div>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
        
        <div v-else class="no-data">
          <div class="empty-state">
            <div class="empty-icon">️️️️️️️️️⚠️</div>
            <p>当前索引暂无数据</p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import '../styles/main-content.css'

export default {
  name: 'MainContent',
  props: {
    selectedIndex: {
      type: String,
      default: ''
    },
    isConnected: {
      type: Boolean,
      required: true
    },
    indexData: {
      type: Object,
      default: () => ({ hits: [], total: 0, took: 0 })
    },
    loadingData: {
      type: Boolean,
      default: false
    },
    currentPage: {
      type: Number,
      default: 1
    },
    pageSize: {
      type: Number,
      default: 10
    },
    total: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      activeTab: 'sql',
      sqlQuery: '',
      dslQuery: '',
      executingSql: false,
      executingDsl: false
    }
  },
  computed: {
    totalPages() {
      return Math.ceil(this.total / this.pageSize);
    }
  },
  methods: {
    prevPage() {
      if (this.currentPage > 1) {
        this.$emit('prev-page');
      }
    },
    nextPage() {
      if (this.currentPage < this.totalPages) {
        this.$emit('next-page');
      }
    },
    formatJson(obj) {
      return this.syntaxHighlight(JSON.stringify(obj, null, 2));
    },
    syntaxHighlight(json) {
      json = json.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
      return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, (match) => {
        let cls = 'number';
        if (/^"/.test(match)) {
          if (/:$/.test(match)) {
            cls = 'key';
          } else {
            cls = 'string';
          }
        } else if (/true|false/.test(match)) {
          cls = 'boolean';
        } else if (/null/.test(match)) {
          cls = 'null';
        }
        return '<span class="' + cls + '">' + match + '</span>';
      });
    },
    copyJson(data) {
      const jsonStr = JSON.stringify(data, null, 2);
      navigator.clipboard.writeText(jsonStr).then(() => {
        alert('JSON已复制到剪贴板');
      }).catch(err => {
        console.error('复制失败:', err);
      });
    },
    executeSql() {
      if (!this.sqlQuery.trim()) return;
      this.executingSql = true;
      this.$emit('execute-sql', this.sqlQuery);
    },
    clearSql() {
      if (confirm('确认清空SQL查询？')) {
        this.sqlQuery = '';
        this.$emit('clear-sql');
      }
    },
    executeDsl() {
      if (!this.dslQuery.trim()) return;
      this.executingDsl = true;
      this.$emit('execute-dsl', this.dslQuery);
    },
    clearDsl() {
      if (confirm('确认清空DSL查询？')) {
        this.dslQuery = '';
        this.$emit('clear-dsl');
      }
    }
  },
  watch: {
    selectedIndex() {
      // 当切换索引时，重置查询
      this.sqlQuery = '';
      this.dslQuery = '';
    }
  }
}
</script>
